﻿using Mes.Pendant.Common.DtoMapping;
using Mes.Pendant.RBACFiles;
using Mes.Pendant.RBACIAppService.UserIAppService.Dto;
using Mes.Pendant.RBACIAppService.UserIAppService.IAppService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Mes.Pendant.RBACAppService.UserAppService
{
	public class UserAppService : ApplicationService, IUserAppService
	{
		private readonly IRepository<User, int> _userRepository;

		public UserAppService(IRepository<User, int> userRepository)
		{
			_userRepository = userRepository;
		}



		public async Task<PagedResult> GetUserList(int page, int limit)
		{
			var userList = await _userRepository.GetListAsync();
			var userListDtoList = userList.MapToList<UserListDto>();
			PagedResult responseResult = new PagedResult();
			responseResult.RowCount = userListDtoList.Count();
			responseResult.PageCount = (int)Math.Ceiling((responseResult.RowCount) / (double)limit);
			responseResult.Queryable = userListDtoList.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).AsQueryable();
			return responseResult;
		}

		public async Task<int> AddUsers(AddUserDto addUserDto)
		{
			var userModel = addUserDto.MapTo<User>();
			var result = await _userRepository.InsertAsync(userModel);
			return 1;
		}

		public async Task<int> DeleteUser(int id)
		{
			await _userRepository.DeleteAsync(id);
			return id;
		}

		public async Task<UpdateUserDto> FindUser(int id)
		{
			var userModel = await _userRepository.GetAsync(id);
			UpdateUserDto updateUserDto = userModel.MapTo<UpdateUserDto>();
			return updateUserDto;
		}

		public async Task<int> UpdateUser(UpdateUserDto updateUserDto)
		{
			var userNameIsExist = await _userRepository.AnyAsync(p => p.UserName == updateUserDto.UserName);
			if (userNameIsExist)
			{
				return -1;
			}
			var userModel = updateUserDto.MapTo<User>();
			var rowNum = _userRepository.UpdateAsync(userModel);
			return updateUserDto.Id;
		}





	}
}
